package com.zeus.core.config.listener;

import com.zeus.common.constants.ZeusConfigConstant;
import com.zeus.common.log.ZeusLoggerConfig;
import com.zeus.core.config.data.ZeusConfig;
import com.zeus.core.factory.ZeusFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Apollo自动更新
 *
 * @author f1ybear_wang  2022/5/7 14:38
 */
public class ZeusAutoUpdateConfigApollo implements ZeusAutoUpdateConfig {
    private final static Logger log = LoggerFactory.getLogger(ZeusAutoUpdateConfigApollo.class);

    public ZeusAutoUpdateConfigApollo() {
        try {

            // 添加apollo配置变化监听
            com.ctrip.framework.apollo.Config config =
                com.ctrip.framework.apollo.ConfigService.getConfig(ZeusConfigConstant.APOLLO_CONFIG_NAMESPACE);
            if (config == null) {
                return;
            }
            config.addChangeListener(changeEvent -> {
                ZeusConfig zeusConfig = ZeusFactory.getZeusConfig();
                if (zeusConfig != null) {
                    zeusConfig.refresh();
                }
            });
            if (log.isInfoEnabled() && ZeusLoggerConfig.needEnableLogger()) {
                log.info(">>> Zeus报警服务, 注册Apollo变化监听器完成");
            }
        } catch (NoClassDefFoundError ignored) {
            // 忽略
        } catch (Throwable e) {
            if (log.isWarnEnabled() && ZeusLoggerConfig.needEnableLogger()) {
                log.warn("### Zeus报警服务, 注册Apollo变化监听出现异常:", e);
            }
        }
    }
}
